package com.new_api;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.NamespaceDescriptor;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class HBaseAPIDemo1 {

    private Configuration conf;
    private Connection conn;
    private Admin admin;

    @Before
    public void beforeTest() throws IOException {
        conf = HBaseConfiguration.create();
        conf.set("hbase.zookeeper.quorum", "node02,node03,node04");
        conn = ConnectionFactory.createConnection(conf);
        admin = conn.getAdmin();
    }

    //删除表
    @Test
    public void deleteTable() throws IOException {
        TableName tableName = TableName.valueOf("api_test:student");
        admin.disableTable(tableName);
        admin.deleteTable(tableName);
    }

    // 创建表
    @Test
    public void createTable() throws IOException {
        TableName tableName = TableName.valueOf("api_test:student");
        TableDescriptorBuilder tableBuilder = TableDescriptorBuilder.newBuilder(tableName);
        boolean flag = admin.tableExists(tableName);
        if (flag) {
            System.out.println("table exists, not create");
            return;
        }
        String[] arr = {"info"};
        List<ColumnFamilyDescriptor> list = new ArrayList<>();
        for (String cf : arr) {
            ColumnFamilyDescriptorBuilder cfBuilder = ColumnFamilyDescriptorBuilder.newBuilder(cf.getBytes());
            cfBuilder.setMaxVersions(1);
            list.add(cfBuilder.build());
        }

        tableBuilder.setColumnFamilies(list);

        admin.createTable(tableBuilder.build());
    }

    // 判断表格是否存在
    @Test
    public void existsTable() throws IOException {
        TableName tableName = TableName.valueOf("default:psn");
        boolean flag = admin.tableExists(tableName);
        System.out.println(flag);
    }

    /**
     * 创建命名空间
     *
     * @throws Exception 套路，先create，再build
     */
    @Test
    public void test1() throws Exception {
        String nameSpace = "api_test";
        NamespaceDescriptor.Builder builder = NamespaceDescriptor.create(nameSpace);
        admin.createNamespace(builder.build());
    }

    @After
    public void afterTest() throws IOException {
        admin.close();
        conn.close();
    }


}
